package com.michael.identifycodetest;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVMobilePhoneVerifyCallback;
import com.avos.avoscloud.AVOSCloud;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;

import junit.framework.Test;


public class MainActivity extends Activity {

    private Button button;

    private Button sureButton;

    private EditText identifyText;

    private EditText phoneEdit;

    private String phoneNum;

    private Button sinaButton;

    private WeiboAuth weiboAuth;

    private SsoHandler ssoHandler;

    private Oauth2AccessToken accessToken;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        weiboAuth = new WeiboAuth(this, FinalConstant.WEIBO_APP_KEY, FinalConstant.WEIBO_CALL_BACK_URL, FinalConstant.WEIBO_SCOPE);

        phoneEdit = (EditText) findViewById(R.id.phone_edit);

        identifyText = (EditText) findViewById(R.id.identify_text);

        sinaButton = (Button) findViewById(R.id.sina_button);

        sinaButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sinaButtonListener();
            }
        });

        sureButton = (Button) findViewById(R.id.sure_button);
        sureButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String identifyNum = identifyText.getText().toString();
                Log.e("验证时，手机号：", phoneNum);
                AVOSCloud.verifySMSCodeInBackground(identifyNum, phoneNum, new AVMobilePhoneVerifyCallback() {

                    @Override
                    public void done(AVException e) {
                        //验证码正确
                        if (e == null) {
                            Toast.makeText(MainActivity.this, "成功了", Toast.LENGTH_SHORT).show();
                        }
                        //验证码错误
                        else {
                            e.printStackTrace();
                            Toast.makeText(MainActivity.this, "失败了", Toast.LENGTH_SHORT).show();

                        }

//                        e.printStackTrace();
                        //此处可以完成用户想要完成的操作
                    }
                });


            }
        });
        button = (Button) findViewById(R.id.identify_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneNum = phoneEdit.getText().toString();
                Log.e("手机号:phoneNum=", phoneNum);
                new SendCodeTask().execute(phoneNum);
            }
        });
    }

    public class SendCodeTask extends AsyncTask<String, Void, Boolean> {
        @Override
        protected Boolean doInBackground(String... params) {
            Log.e("子线程中手机号：", params[0]);
            try {
                AVOSCloud.requestSMSCode(params[0], "文哲哥", "愚人活动", 40);
//                HashMap<String,Object> env = new HashMap<String,Object>();
//                env.put("username","dddd");
//                env.put("appname", "随身云");
//                AVOSCloud.requestSMSCodeInBackgroud(params[0], "观看", env, new RequestMobileCodeCallback() {
//
//                    @Override
//                    public void done(AVException e) {
//                        Log.e("MainActivity:","成功了");
//                        //do something you need
//                    }
//                });

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            if (aBoolean) {
                Toast.makeText(MainActivity.this, "发送成功了", Toast.LENGTH_SHORT).show();
            } else
                Toast.makeText(MainActivity.this, "发送失败了", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 微博登录
     */
    private void sinaButtonListener() {
        AuthListener authListener = new AuthListener();
        ssoHandler = new SsoHandler(MainActivity.this, weiboAuth);
        ssoHandler.authorize(authListener);
    }


    public class AuthListener implements WeiboAuthListener {

        @Override
        public void onComplete(Bundle bundle) {

            //从bundle中解析token
            accessToken = Oauth2AccessToken.parseAccessToken(bundle);
            if (accessToken.isSessionValid()) {

                //这边得获取微博用户的个人信息，调微博的接口，网络请求
                String token = accessToken.getToken();
                String userId = accessToken.getUid();

                Log.e("token=",token+";userId = "+userId);
                Intent intent = new Intent(MainActivity.this, TestActivity.class);
                startActivity(intent);

            } else {
                String code = bundle.getString("code");
                String message = "授权失败";
                if (!TextUtils.isEmpty(code)) {
                    message = message + "\nObtained the code:" + code;
                }
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
            }

        }

        @Override
        public void onCancel() {
            Toast.makeText(MainActivity.this, "取消授权", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onWeiboException(WeiboException e) {
            Toast.makeText(MainActivity.this, "Auth exception :" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 如果不重新写OnActivityResult方法，就会先到登录界面，在到自己想要去的界面
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (ssoHandler != null){
            ssoHandler.authorizeCallBack(requestCode,resultCode,data);
        }
    }

}
